<?php


namespace app\api\controller\v1;
use app\api\exception\BaseException;
use app\api\validate\AfterSalesScene;
use app\api\validate\ExpressScene;
use app\api\validate\RefundScene;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;

/**
 * Class AfterSales
 * @package app\api\controller\v1
 * 售后
 */

class AfterSales extends BaseException
{
    /**
     * 不需要登录方法
     */
    protected $noAuth = [];

    /**
     * 获取售后列表
     */
    public function getAfterSalesList(){
        $data = Request::param();
        $search = [
        ];
        if (isset($data["sort"]) && $data["sort"] == "+id") {
            $order = ["id" => "asc"];
        } else {
            $order = ["id" => "desc"];
        }
        /**
         * 单一模糊查询开始
         */
        //联系人模糊查询
        if (isset($data["username"]) && !empty($data["username"])) {
            $search[] = ["username", "like", "%" . $data["username"] . "%"];
        }
        if (isset($data["service_name"]) && !empty($data["service_name"])) {
            $search[] = ["service_name", "like", "%" . $data["service_name"] . "%"];
        }
        if (isset($data["telephone"]) && !empty($data["telephone"])) {
            $search[] = ["telephone",  "=" ,$data["telephone"]];
        }
        if (isset($data["express_code"]) && !empty($data["express_code"])) {
            $search[] = ["express_code",  "=" ,$data["express_code"]];
        }
        /**
         * 单一模糊查询结束
         */
        /**
         *多条件查询开始
         */
        //数据状态筛选查询
        //  if (isset($data["data_state"]) && $data["data_state"] != '') {
        array_push($search, ["data_state", "=", 1]);
        //}
        if (isset($data["status"]) &&  $data["status"] != '' && $data["status"] != -1) {
            array_push($search, ["status", "=", $data["status"]]);
        }
        if (isset($data["is_notify"]) &&  $data["is_notify"] != '' && $data["is_notify"] != -1 ) {
            array_push($search, ["is_notify", "=", $data["is_notify"]]);
        }
        $result = Db::name("after_sales")->where($search)->order($order)->page($this->page_num, $this->page_limit)->select()->toArray();
        $count = Db::name("after_sales")->where($search)->count();
        foreach ($result as $key => $value){
            if ($result[$key]["goods_class"] != 0){
                $result[$key]["goods_class"] = Db::name("goods_class")->where(["id" => $result[$key]["goods_class"]])->field("id,name")->find();
            }else{
                $result[$key]["goods_class"] = ["name" =>"暂未选择分类"];
            }

        }
        $list = [
            "total" => $count,
            "page" => $this->page_num,
            "limit" => $this->page_limit,
            "list" => $result
        ];
        //Db::name("account")->getLastSql();
        return self::Success($list, '获取成功', 200);
    }

    /**
     * 【ALL】
     * 批量导入售后数据
     */
    public function importAfterSalesData(){

    }

    public function batchDelete()
    {
        $request = Request::param();
        $ids = explode(",", $request["ids"]);
        if (count($ids) != 0) {
            for ($i = 0; $i < count($ids); $i++) {
                $updateData = [
                    "data_state" => 0,
                    "update_time" => date("Y-m-d H:i:s", time()),
                ];
                Db::name("after_sales")->where(["id" => $ids[$i]])->update($updateData);
            }
        }
        return self::Success(null, "删除成功", 200);
    }
    /**
     * 【ALL】
     * 单次添加导入售后数据
     */
    public function addAfterSales(){
        $request = Request::param();
//        try {
//            validate(AfterSalesScene::class)
//                ->scene('add')
//                ->check($request);
//        } catch (ValidateException $e) {
//            // 验证失败 输出错误信息
//            return self::Error(null, $e->getError(), 404);
//        }
        $userInfo = Db::name("account")->where(["user_id" => $this->user_id])->find();
        $insertData = [
            "unpack_time" => isset($request["unpack_time"]) ? $request["unpack_time"] : date("Y-m-d H:i:s", time()),
            "telephone" => isset($request["telephone"]) ? $request["telephone"] : "",
            "username" => isset($request["username"]) ? $request["username"] : "",
            "express_content" => isset($request["express_content"]) ? $request["express_content"]: "",
            "express_name" => isset($request["express_name"]) ? $request["express_name"]: "",
            "content" => isset($request["content"]) ? $request["content"]: "",
            "express_code" => isset($request["express_code"]) ? $request["express_code"]: "",
            "goods_class" => isset($request["goods_class"]) ? $request["goods_class"] : 0,
            "num" => isset($request["num"]) ? $request["num"] : 0,
            "is_notify" => isset($request["is_notify"]) ? $request["is_notify"] : 0,
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
            'user_id' => $this->user_id,
            "service_name" => $userInfo["real_name"],
            'status' => 0,
            'order_id' => isset($request["order_id"]) ? $request["order_id"] : 0,
            'data_state' => 1
        ];
        if (isset($request["order_id"])){
            $updateOrderState = [
                'order_state' => 3,
                'update_time' => date("Y-m-d H:i:s", time()),
            ];
            Db::name("orders")->where(["id" => $request["order_id"]])->update($updateOrderState);
        }
        if (isset($request["type"])){
            $updateStatusState = [
                'status' => 2,
                'update_time' => date("Y-m-d H:i:s", time()),
            ];
            Db::name("express")->where(["id" => $request["express_id"]])->update($updateStatusState);
        }
        $result = Db::name("after_sales")->insert($insertData);
        if ($result) {
            return self::Success(null, "申请成功", 200);
        } else {
            return self::Error(null, '申请失败', 10002);
        }
    }

    /**
     * 【ALL】
     * 批量删除 假删除
     */
    public function batchUpdateState(){
        $request = Request::param();
        try {
            validate(RefundScene::class)
                ->scene('update_state')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "data_state" => $request["data_state"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("after_sales")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("after_sales")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '数据不存在', 10002);
        }
    }

    /**
     *
     * 更改售后数据
     */
    public function updateAfterSalesInfo(){
        $request = Request::param();
        try {
            validate(AfterSalesScene::class)
                ->scene('update')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "unpack_time" => isset($request["unpack_time"]) ? $request["unpack_time"] : date("Y-m-d H:i:s", time()),
            "service_name" => isset($request["service_name"]) ? $request["service_name"] :"",
            "telephone" => isset($request["telephone"]) ? $request["telephone"] : "",
            "username" => isset($request["username"]) ? $request["username"] : "",
            "content" => isset($request["content"]) ? $request["content"]: "",
            "express_content" => isset($request["express_content"]) ? $request["express_content"]: "",
            "express_name" => isset($request["express_name"]) ? $request["express_name"]: "",
            "express_code" => isset($request["express_code"]) ? $request["express_code"]: "",
            "goods_class" => isset($request["goods_class"]) ? $request["goods_class"] : 0,
            "num" => isset($request["num"]) ? $request["num"] : 0,
            "is_notify" => isset($request["is_notify"]) ? $request["is_notify"] : 0,
            'update_time' => date("Y-m-d H:i:s", time()),
        ];
        $result = Db::name("after_sales")->where(["id" => $request["id"]])->update($updateData);
        if ($result) {
            return self::Success(null, "更新成功", 200);
        } else {
            return self::Error(null, '更新成功', 10002);
        }
    }

    public function updateAfterSalesIsNotify(){
        $request = Request::param();
        try {
            validate(RefundScene::class)
                ->scene('update_state')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "is_notify" => $request["is_notify"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("after_sales")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("after_sales")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '数据不存在', 10002);
        }
    }
}